import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:ui';
import 'dart:async';
import 'package:dio/dio.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter/services.dart';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_yres/tool/star.dart';
import 'package:flutter_yres/model/car/car_merchant_entity.dart';
import 'package:flutter_yres/pages/user/ArticleDetail.dart';

class MerchantDetailPage extends StatefulWidget {
  CarMerchantModelData model;
  MerchantDetailPage({Key key, this.model}) : super(key: key);

  @override
  _MerchantDetailPageState createState() => _MerchantDetailPageState(model);
}

class _MerchantDetailPageState extends State<MerchantDetailPage> {
  Timer _timer;
  CarMerchantModelData model;
  List articles = new List();
  List banner = new List();
  int current = 0;
  _MerchantDetailPageState(this.model);
  Map merchant_msg = new Map();
  Map merchant_detail = new Map();
  Map introduce = new Map();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: new AppBar(
          backgroundColor: Colors.white,
          brightness: Brightness.light,
          centerTitle: true,
          title: Text('商家详情'),
          iconTheme: new IconThemeData(color: Colors.black),
          elevation: 0.5,
          actions: <Widget>[],
        ),
        body: Container(
            color: f0Color,
            child: SingleChildScrollView(
                child: Column(children: <Widget>[
              Container(
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(4)),
                alignment: Alignment.centerLeft,
                width: ScreenUtil.getInstance().setWidth(750),
                margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(20)),
                // color: Colors.white,
                child: Column(
                  children: <Widget>[
                    Container(
                      alignment: Alignment.centerLeft,
                      padding: EdgeInsets.all(ScreenUtil.getInstance().setWidth(10)),
                      child: Text(
                        model.merchant_name,
                        textAlign: TextAlign.left,
                        style: TextStyle(color: Colors.black, fontSize: 17),
                      ),
                    ),
                    Row(
                      children: <Widget>[
                        Padding(
                          padding: EdgeInsets.all(ScreenUtil.getInstance().setWidth(10)),
                          child: new StaticRatingBar(
                            size: 15.0,
                            rate: double.parse(model.comment_score),
                          ),
                        ),
                        RichText(
                          text: TextSpan(
                              style: TextStyle(color: Colors.grey),
                              children: [
                                TextSpan(
                                    text: model.comment_score + '分',
                                    style: TextStyle(fontSize: 15.0)),
                              ]),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                        RichText(
                          text: TextSpan(
                              style: TextStyle(fontSize: 13.0),
                              children: [
                                TextSpan(
                                    text: '¥' + model.consumption + '/人',
                                    style: TextStyle(color: Colors.grey)),
                              ]),
                        ),
                        Expanded(
                            child: Container(
                          margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(8)),
                          alignment: Alignment.bottomRight,
                          child: Text('销量' + model.sales_num,
                              style: TextStyle(
                                  fontSize: 14.0, color: Colors.orange)),
                        )),
                      ],
                    ),
                    Container(
                        //横向滑动列表
                        color: Colors.white,
                        margin: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setHeight(DP_10),
                          0,
                          ScreenUtil.getInstance().setHeight(DP_10),
                          0,
                        ),
                        height: 100.0,
                        child: ListView(
                          //设置水平方向排列
                          scrollDirection: Axis.horizontal,
                          //添加子元素
                          children: <Widget>[
                            imgGrid()
                            // Container(
                            //   width: 100,
                            //   color: Colors.lightBlue,
                            // ),
                            // Container(
                            //   width: 100,
                            //   color: Colors.amber,
                            // ),
                            // Container(
                            //   width: 100,
                            //   color: Colors.pinkAccent,
                            // ),
                          ],
                        )),
                    Row(
                      children: <Widget>[
                        Container(
                            margin:
                                EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(10), 0, ScreenUtil.getInstance().setWidth(10), 0),
                            child: Image.asset(
                              'images/icon_nav_location.png',
                              width: 13,
                              height: 15,
                              fit: BoxFit.fill,
                            )),
                        Expanded(
                          child: Text(
                            // merchants[index].province +
                            model.city + model.county + model.detail_address,
                            style:
                                TextStyle(color: Colors.grey, fontSize: 13.0),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        // Image.asset(
                        //   'images/icon_nav_location.png',
                        //   width: 13,
                        //   height: 15,
                        //   fit: BoxFit.fill,
                        // ),
                      ],
                    ),
                    Container(
                      height: 15,
                    )
                  ],
                ),
              ),
              Container(
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(4)),
                padding: EdgeInsets.only(top: 10, bottom: 10),
                margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(20)),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Container(
                      padding: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setHeight(DP_10),
                          2,
                          ScreenUtil.getInstance().setHeight(DP_10),
                          2),
                      margin: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setHeight(DP_20),
                          0,
                          ScreenUtil.getInstance().setHeight(DP_20),
                          0),
                      child: Text('公告',
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE))),
                      decoration: BoxDecoration(
                          color: Color.fromARGB(255, 233, 63, 51),
                          borderRadius: BorderRadius.circular(4)),
                    ),
                    Expanded(
                        child: GestureDetector(
                      child: Text(
                        articles.length == 0 ? "" : articles[current]['title'],
                        style: TextStyle(
                            color: Colors.black87,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(SMALL_FONT_SIZE)),
                      ),
                      onTap: () {
                        Navigator.of(context)
                            .push(MaterialPageRoute(builder: (context) {
                          return new ArticleDetailPage(
                            article_id: articles[current]['merchant_notice_id'],
                          );
                        }));
                      },
                    ))
                  ],
                ),
              ),
            ]))));
  }

  Widget imgGrid() {
    List<Widget> tiles = []; //先建一个数组用于存放循环生成的widget
    Widget content; //单独一个widget组件，用于返回需要生成的内容widget

    for (var item in banner) {
      tiles.add(Container(
        width: 100,
        color: f0Color,
        child: Image.network(
                Api.BaseUrl + item['img']
              ),
      ));
    }
    content = new Row(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  Widget _pd(Widget w, {double l, double t, double r, double b}) {
    //边距
    return Padding(
        padding: EdgeInsets.fromLTRB(
            ScreenUtil.getInstance().setWidth(l) ?? 0,
            ScreenUtil.getInstance().setHeight(t) ?? 0,
            ScreenUtil.getInstance().setWidth(r) ?? 0,
            ScreenUtil.getInstance().setHeight(b) ?? 0),
        child: w);
  }

  @override
  void initState() {
    _getDetail();
    _getIntroduc();
    _getNotice(); //获取公告列表
    _getBanner(); //获取商户Banner/广告图列表
    super.initState();
  }

  _getDetail() async {
    FormData data = new FormData.fromMap({'merchant_id': model.merchant_id});
    Response<String> response =
        await HttpUtil().post(Api.GetMerchanTMsgUrl, data: data);
    Map userMap = json.decode(response.data);

    if (userMap['code'] == 1) {
      if (mounted) {
        setState(() {
          merchant_msg = userMap['data']['merchant_msg'];
          merchant_detail = userMap['data']['merchant_detail'];
        });
      }
    }
  }

  _getIntroduc() async {
    FormData data = new FormData.fromMap({'merchant_id': model.merchant_id});
    Response<String> response =
        await HttpUtil().post(Api.GetIntroducUrl, data: data);
    Map userMap = json.decode(response.data);

    if (userMap['code'] == 1) {
      if (mounted) {
        setState(() {
          if (userMap['data']['introduce'] is Map) {
            introduce = userMap['data']['introduce'];
          }
        });
      }
    }
  }

  _getNotice() async {
    FormData data = new FormData.fromMap({'merchant_id': model.merchant_id});
    Response<String> response =
        await HttpUtil().post(Api.GetMerchantNoticeListUrl, data: data);
    Map userMap = json.decode(response.data);
    if (userMap['code'] == 1) {
      if (mounted) {
        startTimer();
        setState(() {
          articles.addAll(userMap['data']['list']);
          current = 0;
        });
      }
    }
  }

  _getBanner() async {
    FormData data = new FormData.fromMap({'merchant_id': model.merchant_id});
    Response<String> response =
        await HttpUtil().post(Api.GetMerchantBannerListUrl, data: data);
    Map userMap = json.decode(response.data);
    if (userMap['code'] == 1) {
      if (mounted) {
        banner.addAll(userMap['data']['list']);
      }
    }
  }

  void startTimer() {
    const period = const Duration(seconds: 5);
    _timer = Timer.periodic(period, (timer) {
      setState(() {
        if (current == (articles.length - 1)) {
          current = 0;
        } else {
          current++;
        }
      });
    });
  }

  void cancelTimer() {
    if (_timer != null) {
      _timer.cancel();
      _timer = null;
    }
  }

  @override
  void dispose() {
    super.dispose();
    cancelTimer();
    // WidgetsBinding.instance.removeObserver(this);
  }
}
